const extendArticleType = require("../sequelize/extendArticleType");
const extendArticle = require("../sequelize/extendArticle");

class Service {
	async list(query) {
		try {
			const pageNum = parseInt(query.pageNum) || 1;
			const pageSize = parseInt(query.pageSize) || 10;

			const rows = await extendArticleType.findAndCountAll({});
			return {
				code: 200,
				message: "ok",
				result: {
					list: await extendArticleType.findAll({
						limit: pageSize,
						offset: (pageNum - 1) * pageSize,
					}),
					count: rows.count,
				},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async getTypeListAndArticle(query) {
		try {
			return {
				code: 200,
				message: "ok",
				result: {
					list: await extendArticleType.findAll({
						include: [
							{
								model: extendArticle,
							},
						],
					}),
				},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async add(body) {
		try {
			await extendArticleType.create({ ...body });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async update(body) {
		try {
			await extendArticleType.update(body, { where: { id: body.id } });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async del(id) {
		try {
			await extendArticleType.destroy({
				where: {
					id,
				},
			});
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}
}

module.exports = new Service();
